import Vue from 'vue'
import Vuex from 'vuex'

// 导入各个模块
import dataView from './modules/dataView'
import user from './modules/user'
import ui from './modules/ui'
import dataImport from './modules/dataImport'
import logs from './modules/logs'

Vue.use(Vuex)

export default new Vuex.Store({
  // 严格模式，在开发环境下开启
  strict: process.env.NODE_ENV !== 'production',

  // 全局状态
  state: {
    loading: false,
    error: null,
    version: '1.0.0'
  },

  // 全局 getters
  getters: {
    isLoading: state => state.loading,
    hasError: state => !!state.error,
    appVersion: state => state.version
  },

  // 全局 mutations
  mutations: {
    SET_LOADING(state, loading) {
      state.loading = loading
    },

    SET_ERROR(state, error) {
      state.error = error
    },

    CLEAR_ERROR(state) {
      state.error = null
    }
  },

  // 全局 actions
  actions: {
    setLoading({ commit }, loading) {
      commit('SET_LOADING', loading)
    },

    setError({ commit }, error) {
      commit('SET_ERROR', error)
    },

    clearError({ commit }) {
      commit('CLEAR_ERROR')
    },

    // 异步初始化应用
    async initializeApp({ dispatch }) {
      try {
        // 初始化各个模块
        await dispatch('dataView/initializeData')
        await dispatch('user/checkAuth')
        await dispatch('dataImport/initializeImportData')
        await dispatch('logs/initializeLogs')

        console.log('应用初始化完成')
      } catch (error) {
        console.error('应用初始化失败:', error)
        dispatch('setError', error.message)
      }
    }
  },

  // 模块
  modules: {
    dataView,
    user,
    ui,
    dataImport,
    logs
  }
})
